import { Injectable, Inject } from '@nestjs/common';
import {
  Menu,
  CreateMenuDto,
  UpdateMenuDto,
  menuModelReturnType,
  PaginationDto
} from '@schemas';

@Injectable()
export class MenuService {
  constructor(
    @Inject(Menu.name)
    private readonly menu: menuModelReturnType
  ) {}
  create(createMenuDto: CreateMenuDto) {
    return this.menu.create(createMenuDto);
  }

  findAll() {
    return this.menu.find();
  }
  async pageQuery(dto?: PaginationDto) {
    const data = await this.findAll();
    // const tree = arrayToTree(data, {
    //   parentProperty: 'parentId',
    //   customID: '_id',
    //   childrenProperty: 'children'
    // });
    // console.log(dto, tree);
    return {
      list: data,
      total: data.length
    };
  }

  // ? 递归构建树形结构
  private buildTree(list: any[], rootVal: string | null = null) {
    const arr = [];
    list.forEach((item) => {
      if (item.parentId == rootVal) {
        const children = this.buildTree(list, item._id);
        if (children.length) {
          item.children = children;
        }
        arr.push(item);
      }
    });
    return arr;
  }

  findOne(id: string) {
    return this.menu.findById(id);
  }

  findListByIds(ids: string[]) {
    return this.menu.find({ _id: { $in: ids } });
  }

  findIds() {
    return this.menu.find().distinct('_id');
  }

  update(id: string, updateMenuDto: UpdateMenuDto) {
    return this.menu.findByIdAndUpdate(id, updateMenuDto);
  }

  remove(id: string) {
    return this.menu.findByIdAndDelete(id);
  }
}
